<template>
  <view>
    <uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="20px 20px 0 0" @close="close" >
      <view class="container">
        <!-- 商品信息相关 -->
        <view class="top-box">
          <image :src="skuImg" mode="aspectFill"/>
          <view>
            <view>￥{{skuPrice}}</view>
            <view>{{skuNameStr}}</view>
          </view>
        </view>
        <!-- sku相关 -->
        <view class="sku-box">
          <view v-for="(item,index) in skuData.skuKeys" :key="index">
            <view class="sku-key-box">{{ item.keyName }}</view>
            <view class="sku-value-box">
              <view class="sku-value-item" 
                v-for="(m,i) in item.skuValues" :key="i"
                :style="{
                  backgroundColor: skuIndexList[index] == i ? 'red' : (m.disabled ? '#eff3f6' : '#fff'),
                  borderColor: skuIndexList[index] == i ? 'transparent' : (m.disabled ? 'lightgray' : 'black'),
                  color: skuIndexList[index] == i ? '#fff' : (m.disabled ? 'lightgray' : 'black'),
                  pointerEvents: m.disabled ? 'none' : 'all',
                }"
                @click="didSelectedItem(m,i,index)"
              >
                {{ m.valueName }}
              </view>
            </view>
          </view>
        </view>
        <!-- 占位 -->
        <view style="height: 188rpx;margin-top: 30rpx;"></view>
        <!-- 数量、购买、加入购物车 -->
        <view class="bottom-box">
          <view class="num-out-box">
            <view>数量：</view>
            <view class="num-box">
              <view @click="reduce">-</view>
              <input type="text" v-model="number">
              <view @click="add">+</view>
            </view>
          </view>
          <view class="cart-buy-box">
            <view class="cart" @click="addCart">加入购物车</view>
            <view class="buy" @click="buyNow">立即购买</view>
          </view>
        </view>
      </view>
    </uni-popup>
  </view>
</template>

<script>
import UniPopup from '../uni-popup/uni-popup.vue';
export default {
  props: {
    skuData: {
      type: Object,
      default: ()=> {}
    }
  },
  components: {
    UniPopup,
  },
  data() {
    return {
      // 存放所有可能的sku组合list
      skuCombList: [],
      // 记录选中的规格名称
      skuNameList: [],
      // 记录选中的规格id
      skuIdList: [],
      // 记录选中的规格的index，用于区分选中和非选中状态
      skuIndexList: [],
      // 默认数量
      number: 1,
    };
  },
  computed: {
    skuImg() {
      return this.skuObj ? this.skuObj.skuImg : this.skuData.productImg
    },
    skuNameStr() {
      return this.skuNameList.join(' ').trim() ? '已选：' + this.skuNameList.join(' ') : '请选择规格'
    },
    skuPrice() {
      return this.skuObj ? this.skuObj.skuPrice : this.skuData.productPrice
    },
    skuObj() {
      return this.skuData.combs.filter(m => m.comb == this.skuIdList.join(','))[0] 
    }
  },
  mounted() {
    this.initPossibleSkuCombList()

    this.setSkuDisableState(-1)

    this.setDefaultSelectedSku()
  },
  methods: {
    open() {
      this.$refs.popup.open()
    },
    close() {
      this.$refs.popup.close()
    },
    // 设置默认选中的sku
    setDefaultSelectedSku() {
      if (this.skuData.combs.length > 0) {
        let comb = this.skuData.combs[0]
        let arr = [...comb.comb.split(',')]
        arr.forEach(value => {
          let obj = this.getClickIndex(value)
          this.didSelectedItem(obj.item, obj.index, obj.idx)
        })
      }
    },
    // 模拟点击事件
    getClickIndex(valueId) {
      let obj = {}
      this.skuData.skuKeys.forEach((value, index) => {
        value.skuValues.forEach((val, idx) => {
          if (val.valueId == valueId) {
            obj.item = val
            obj.idx = index
            obj.index = idx
          }
        })
      })
      return obj
    },
    // 初始化可能的sku组合
    initPossibleSkuCombList() {
      this.skuData.combs.map(m => m.combName).forEach(m => {
        let res = this.processDataCombine([],0,m.split(','),[])
        this.skuCombList.push(...res.slice())
      })
    },
    // 处理数据一共有多少种排列可能
    processDataCombine(current = [], index = 0,arr = [],result = []) {
      result.push(current.slice().join(','));
      for (let i = index; i < arr.length; i++) {
        current.push(arr[i]);
        this.processDataCombine(current, i + 1,arr,result);
        current.pop();
      }
      return result.filter(m => m.length != 0)
    },
    // skuItem点击事件
    didSelectedItem(skuValue,valueIndex,keyIndex) {
      let isEqual = this.skuIdList[keyIndex] == skuValue.valueId 

      this.$set(this.skuIdList,keyIndex,isEqual ? '' : skuValue.valueId)
      this.$set(this.skuNameList,keyIndex,isEqual ? '' : skuValue.valueName)
      this.$set(this.skuIndexList,keyIndex,isEqual ? -1 : valueIndex)

      this.setSkuDisableState(keyIndex)

      this.$emit('sku-str',this.skuNameStr)
      if (this.skuObj) {
        this.$emit('sku-ready',this.skuObj)
      }
    },
    // 设置sku的可点击性
    setSkuDisableState(tapIndex) {
      this.skuData.skuKeys.forEach((keyValue, keyIndex) => {
        if (keyIndex == tapIndex) return
        keyValue.skuValues.forEach((skuValue, skuIndex) => {
          if (this.skuIndexList[keyIndex] != -1 && skuIndex == this.skuIndexList[keyIndex]) return
          let skuNameList = [...this.skuNameList.slice()];
					this.$set(skuNameList, keyIndex, skuValue.valueName);
					let skuNameRemoveEmptyStr = skuNameList.filter(item => item !== '' && typeof item !== 'undefined').join(',');
          skuValue.disabled = !this.skuCombList.includes(skuNameRemoveEmptyStr)
        })
      })
    },
    // 减少数量
    reduce() {
      if (this.number <= 1) {
        this.showToast('商品数量最小为1')
        return
      }
      this.number--
    },
    // 增加数量
    add() {
      if (!this.skuObj) {
        this.showToast()
        return
      }
      if (this.number >= this.skuObj.skuNum) {
        this.showToast('超出所选规格最大库存')
        return
      }
      this.number++
    },
    // 添加到购物车
    addCart() {
      if (!this.skuObj) {
        this.showToast()
        return
      }
      if (this.skuObj.skuNum < this.number) {
        this.showToast('超出所选规格最大库存')
        return
      }
      this.$emit('add-cart',{...this.skuObj,productNum: this.number})
    },
    // 立即购买
    buyNow() {
      if (!this.skuObj) {
        this.showToast()
        return
      }
      if (this.skuObj.skuNum < this.number) {
        this.showToast('超出所选规格最大库存')
        return
      }
      this.$emit('buy-now',{...this.skuObj,productNum: this.number})
    },
    showToast(title = '请将规格选择完整') {
      uni.showToast({
        title,
        icon: 'none',
      })
    }
  },
}
</script>

<style lang="scss" scoped>
.container {
  background-color: white;
  border-radius: 20rpx 20rpx 0 0;
	padding: 150rpx 0rpx 20rpx;
  position: relative;
}
.sku-box {
  max-height: 600rpx;
  overflow: auto;
  padding: 0 30rpx;
}
.top-box {
  position: absolute;
  top: -30rpx;
  width: 690rpx;
  display: flex;
  left: 30rpx;
  image {
    border-radius: 15rpx;
    width: 160rpx;
    height: 160rpx;
    display: block;
  }
  view {
    margin-left: 10rpx;
    display: flex;
    flex-direction: column;
    justify-content: flex-end;
  }
}
.sku-key-box {
  margin-bottom: 20rpx;
  font-weight: bold;
}
.sku-value-box {
  display: flex;
  flex-wrap: wrap;
}
.sku-value-item {
  border: 1px solid #000;
  padding: 10rpx 25rpx;
  margin-right: 15rpx;
  margin-bottom: 20rpx;
  border-radius: 9999px;
  font-size: 28rpx;
}
.active {
  border: 1px red solid;
  background-color: red;
  color: white;
}
.disabled {
  background-color: lightgray;
  border: 1px solid lightgray;
  color: white;
  pointer-events: none;
}
.bottom-box {
  margin: 0 30rpx;
  position: absolute;
  width: 690rpx;
  bottom: 10px;
}
.num-out-box {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 20rpx 0;
  background-color: white;
}
.num-box {
  display: flex;
  align-items: center;
  border: 1px #00000030 solid;
  border-radius: 5rpx;
  margin-bottom: 20rpx;
  margin-top: 10rpx;
  view {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 60rpx;
    height: 60rpx;
  }
  view:first-child {
    border-right: 1px #00000030 solid;
  }
  view:last-child {
    border-left: 1px #00000030 solid;;
  }
  input {
    width: 69rpx;
    text-align: center;
  }
}
.cart-buy-box {
  display: flex;
  font-size: 28rpx;
  width: 100%;
  view {
    flex: 1 1 0%;
    display: flex;
    align-items: center;
    justify-content: center;
    height: 88rpx;
    color: white;
  }
  .cart {
    background-color: orange;
    border-radius: 44rpx 0 0 44rpx;
  }
  .buy {
    background-color: red;
    border-radius: 0 44rpx 44rpx 0;
  }
}                                                                                                                                                                 
</style>